import random

from Autotests.Suites.StressTest.Logger import Logger
from Autotests.Suites.StressTest.Selector.GroupSwitchTimer import GroupSwitchTimer
from Config.RunConfig import RunConfig, Options
from Autotests.Suites.StressTest.Selector.OperationsGroupSelector import OperationGroups


class GroupSelector:
    def __init__(self):
        self._operationsMaxCount = 100
        self._randomScenario = 'Random'
        self._groupScenario = 'Group'

    def selectScenario(self, manserv, partnerId):
        scenarioType = RunConfig().get(Options.StressTest.scenarioType)
        if scenarioType == self._randomScenario:
            self._selectRandomScenario(manserv, partnerId)
        if scenarioType == self._groupScenario:
            self._selectGroupScenario(manserv, partnerId, RunConfig().get(Options.StressTest.onlyClientGroup))

    def _executeOperation(self, manserv, randomOperation, partnerId):
        try:
            Logger.logBegin(randomOperation)
            randomOperation(manserv, partnerId)
            Logger.logEnd(randomOperation, True)
        except:
            Logger.logEnd(randomOperation, False)

    def _selectRandomScenario(self, manserv, partnerId):
        operationsCount = random.randint(1, self._operationsMaxCount)
        for operation in range(1, operationsCount):
            operationsGroup = OperationGroups().getRandomOperationsGroup()
            randomOperation = operationsGroup._getRandomOperation()
            self._executeOperation(manserv, randomOperation, partnerId)

    def _selectGroupScenario(self, manserv, partnerId, onlyClient):
        groupIndex = GroupSwitchTimer.getGroupIndex()
        if onlyClient == 'True':
            groupIndex = OperationGroups().getClientIndex()
        operationsGroup = OperationGroups().operationsGroup[groupIndex]()
        randomOperation = operationsGroup._getRandomOperation()
        self._executeOperation(manserv, randomOperation, partnerId)
